var Mextractr = (function() {

return {
  extract : function(text, callback, errback) {
    jQuery.ajax({
      type : "POST",
      url : this.endpointUrl,
      data: {
        output : 'atom',
        apikey : this.apiKey,
        text : text.replace(/[\\n\\r]/g,' ')
      },
      dataType : "xml",
      error : errback,
      success: extractMetadata
    });

    function extractMetadata(doc) {
      try {
        var result = {}
        result.whos = Array.prototype.slice.apply(doc.getElementsByTagName('gd:who')).map(function(w) { 
          w = w.getAttribute('valueString');
          var isCompany = w.charAt(0)=='*';
          return { value : isCompany ? w.substring(1) : w, isCompany : isCompany };
        });
        result.wheres = Array.prototype.slice.apply(doc.getElementsByTagName('gd:where')).map(function(w) { 
          return { value : w.getAttribute('valueString') }
        });
        result.whens = Array.prototype.slice.apply(doc.getElementsByTagName('gd:when')).map(function(w) { 
          return { value : w.getAttribute('valueString'),
                   startTime : w.getAttribute('startTime'), 
                   endTime : w.getAttribute('endTime') };
        });

        callback(result);
      } catch (e) {
        errback(e);
      }
    }
  },
  endpointUrl : 'http://api.emetadata.net/mextractr',
  apiKey : '7288372075BC74056F9C9F3F1B0B73ECB0C839C7'
}

})();


/**
 *
 */
var MextractrPlugin = {
  execute : function(env, callback, errback) {
    if (env.selectedText) {
      Mextractr.extract(env.selectedText, handleMetadata, errback);
    /*
    } else if (env.locationUrl) {
      $.ajax({
        url : env.locationUrl,
        dataType : 'text',
        success : handleUrlContent,
        error : _errback
      })
    */
    } else {
      callback();
    }

    /*
    function handleUrlContent(text) {
      Mextractr.extract(text, handleMetadata, _errback);
    }
    */

    function handleMetadata(metadata) {
      if (metadata.wheres.length>0) {
        env.address = metadata.wheres[0].value;
      }
      callback();
    }
  }
}

SocialDashboard.registerPlugin(MextractrPlugin)


